package com.cloudspace.jindun.activity;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.cloudspace.jindun.JindunApp;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.constants.Constants;
import com.cloudspace.jindun.ext.aq.AQUtility;
import com.cloudspace.jindun.fragment.DialFragment;
import com.cloudspace.jindun.fragment.InterPhoneFragment;
import com.cloudspace.jindun.fragment.LocateFragment;
import com.cloudspace.jindun.fragment.MessageFragment;
import com.cloudspace.jindun.fragment.WoyaoFragment;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.manager.MessageNumberManager;
import com.cloudspace.jindun.model.Friends;
import com.cloudspace.jindun.network.url.YXHttpUrl;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.ToastMaker;
import com.google.gson.Gson;
import com.nineoldandroids.view.ViewHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;
import okhttp3.Call;

import static com.cloudspace.jindun.utils.Utility.getSDPath;

public class MainActivity extends CustomTitleBaseActivity implements RadioGroup.OnCheckedChangeListener, RongIM.UserInfoProvider {
    private RadioGroup mRadioGroup;
    private DialFragment mDianhuaFragment;//电话
    private LocateFragment mDingweiFragment;//定位
    private InterPhoneFragment mInterPhoneFragment;//对讲机
    private WoyaoFragment mWoyaoFragment; //我要
    private MessageFragment mMessageFragment;//消息
    private DrawerLayout drawerLayout;//抽屉

    private ImageView mRedDotIv;

    private Button mJbtnHome;
    SharedPreferences sharedPreferences;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private Friends friends=null;

    private View.OnClickListener radioButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == null || v.getTag() == null){
                return;
            }

            int index = (int) v.getTag();

            if (index == 3){
                showRedDotView(false);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jd_main_activity, false);

        if (UserSessionManager.getCurrentLoginUser() == null){
            RegisterActivity.showActivity(this);
            return;
        }

        initView();
        setListener();
        viewMonitor();

        iniFriendData();
        RongIM.setUserInfoProvider(this, true);
    }

    public void showRedDotView(final boolean show){
        AQUtility.post(new Runnable() {
            @Override
            public void run() {
                if (mRedDotIv != null){
                    mRedDotIv.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            }
        });
    }

    private BroadcastReceiver messageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            APPLog.zxhLog(TAG + " messageReceiver receive");
            showRedDotView(MessageNumberManager.getInstance().isMessageUnread());
        }
    };

   //获取好友数据
    private void iniFriendData() {
        OkHttpUtils.get()
                .url(YXHttpUrl.SERVER_URI+"phone/"+UserSessionManager.getInstance().getUserId()+"/isPer")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {

                        if (response != null) {
                            Gson gson = new Gson();
                            if (gson.fromJson(response, Friends.class) != null) {

                                friends = gson.fromJson(response, Friends.class);
                                RongIM.setUserInfoProvider(MainActivity.this, true);
                            }
                        }


                    }
                });
    }


    private void setListener() {
        mRadioGroup.setOnCheckedChangeListener(this);
    }

    private void initView() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        mRadioGroup = (RadioGroup) findViewById(R.id.rg_main1_radioGroup);
        mJbtnHome = (Button) findViewById(R.id.jd_btn_home);

        mRedDotIv = (ImageView) findViewById(R.id.reddot_iv);
        RelativeLayout.LayoutParams redDotParams = (RelativeLayout.LayoutParams) mRedDotIv.getLayoutParams();
        redDotParams.rightMargin = (int) (JindunApp.getInstance().getScreenWidth()/5*1.25);
        mRedDotIv.setLayoutParams(redDotParams);

        mRadioGroup.bringToFront();
        mJbtnHome.bringToFront();
        mRedDotIv.bringToFront();

        select(0);
        ((RadioButton) mRadioGroup.getChildAt(0)).setChecked(true);
        sharedPreferences = getSharedPreferences("num", MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        if (UserSessionManager.getCurrentLoginUser().getUserPhone() != null) {
            String userPhone = UserSessionManager.getCurrentLoginUser().getUserPhone();
            edit.putString("phone", userPhone);
            edit.commit();
        }

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int count = group.getChildCount();
        for (int i = 0; i < count; i++) {
            RadioButton button = (RadioButton) mRadioGroup.getChildAt(i);

            button.setTag(i);

            button.setOnClickListener(radioButtonClickListener);

            if (button.isChecked()) {
                select(i);
                button.setChecked(true);
                break;
            }
        }
    }


    boolean isType = true;

    private void select(int i) {
        //实例事物
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        switch (i) {
            case 0:
                if (mDianhuaFragment == null) {
                    mDianhuaFragment = new DialFragment();
                }
                transaction.replace(R.id.fl_main1_fragment, mDianhuaFragment, "mDianhuaFragment");

                break;
            case 1:
                if (mInterPhoneFragment == null) {
                    mInterPhoneFragment = new InterPhoneFragment();
                }
                transaction.replace(R.id.fl_main1_fragment, mInterPhoneFragment, "mInterPhoneFragment");
                break;
            case 2:
                if (mWoyaoFragment == null) {
                    mWoyaoFragment = new WoyaoFragment();
                }
                transaction.replace(R.id.fl_main1_fragment, mWoyaoFragment, "mWoyaoFragment");

                break;
            case 3:
                if (mMessageFragment == null) {
                    mMessageFragment = new MessageFragment();
                }

                showRedDotView(false);

                transaction.replace(R.id.fl_main1_fragment, mMessageFragment, "mMessageFragment");
                break;

            case 4:
                if (mDingweiFragment == null) {
                    mDingweiFragment = new LocateFragment();
                }
                transaction.replace(R.id.fl_main1_fragment, mDingweiFragment, "mDingweiFragment");
                break;

            default:
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void viewMonitor() {

        drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerStateChanged(int newState) {
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                View mContent = drawerLayout.getChildAt(0);
                View mMenu = drawerView;
                float scale = 1 - slideOffset;
                float rightScale = 0.8f + scale * 0.2f;

                if (drawerView.getTag().equals("LEFT")) {

                    float leftScale = 1 - 0.3f * scale;

//                    ViewHelper.setScaleX(mMenu, leftScale);
//                    ViewHelper.setScaleY(mMenu, leftScale);
                    ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
                    ViewHelper.setTranslationX(mContent,
                            mMenu.getMeasuredWidth() * (1 - scale));
                    ViewHelper.setPivotX(mContent, 0);
                    ViewHelper.setPivotY(mContent,
                            mContent.getMeasuredHeight() / 2);
                    mContent.invalidate();
//                    ViewHelper.setScaleX(mContent, rightScale);
//                    ViewHelper.setScaleY(mContent, rightScale);
                } else {
                    ViewHelper.setTranslationX(mContent,
                            -mMenu.getMeasuredWidth() * slideOffset);
                    ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());
                    ViewHelper.setPivotY(mContent,
                            mContent.getMeasuredHeight() / 2);
                    mContent.invalidate();
//                    ViewHelper.setScaleX(mContent, rightScale);
//                    ViewHelper.setScaleY(mContent, rightScale);
                }

            }

            @Override
            public void onDrawerOpened(View drawerView) {
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                drawerLayout.setDrawerLockMode(
                        DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();

        unregisterReceiver(downloadCompleteReceiver);
        LocalBroadcastManager.getInstance(JindunApp.getInstance()).unregisterReceiver(messageReceiver);
    }

    @Override
    protected void onStart() {
        super.onStart();

        registerReceiver(downloadCompleteReceiver,
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        LocalBroadcastManager.getInstance(JindunApp.getInstance()).registerReceiver(messageReceiver,
                new IntentFilter(Constants.MESSAGE_BROADCAST));
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction()
                == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastMaker.showToastShort(R.string.exit_tip);
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void click(View view) {
        select(2);
        ((RadioButton) mRadioGroup.getChildAt(2)).setChecked(true);
    }

    public final static String TAG = MainActivity.class.getSimpleName();


    @Override
    protected void onResume() {
        super.onResume();

        iniFriendData();

        showRedDotView(MessageNumberManager.getInstance().isMessageUnread());
    }

//    private void requestData(String url, String userId) {
//        OkHttpUtils.get()
//                .url(url + userId)
//                .build()
//                .execute(new StringCallback() {
//                    @Override
//                    public void onError(Call call, Exception e, int id) {
//                        ToastMaker.showToastShort(R.string.generic_error);
//                    }
//
//                    @Override
//                    public void onResponse(String response, int id) {
//                        if (response != null) {
//                            Gson gson = new Gson();
//                            if (gson.fromJson(response, PersonalData.class) != null) {
//                                PersonalData personalData = gson.fromJson(response, PersonalData.class);
//                                GlobalValue.ins().setPersonalData(personalData);
//
//                                if (personalData.getData() != null){
//                                    GlobalValue.ins().setPhone(personalData.getData().getUserPhone());
//                                }
//                            }
//                        }
//                    }
//                });
//    }
//上传好友数据给融云
    @Override
    public UserInfo getUserInfo(String s) {
        if (friends != null && friends.getData().size() > 0) {

            for (Friends.DataBean dataBean : friends.getData()) {
                if (dataBean.getUserId().equals(s)) {
                    return new UserInfo(dataBean.getUserId(), dataBean.getUserName(),Uri.parse(dataBean.getIconUrl()));
                }
            }
        }
        return null;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode, data);
        if (mInterPhoneFragment != null){
            mInterPhoneFragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    public  static long downloadId = 0;
    private BroadcastReceiver downloadCompleteReceiver =  new  BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            /**
             * get the id of download which have download success, if the id is
             * my id and it's status is successful, then install it
             **/

            long completeDownloadId = intent.getLongExtra(
                    DownloadManager.EXTRA_DOWNLOAD_ID, -1);

            APPLog.zxhLog(TAG + String.format("downloadCompleteReceiver onReceive:%d, %d", completeDownloadId, downloadId));
            if (completeDownloadId == downloadId) {
                // if download successful, install apk
                install(context);
            }
        }
    };

    public void install(Context context) {
        Intent i = new Intent(Intent.ACTION_VIEW);

        String filePath = getSDPath().getAbsolutePath()+"/.jindun/apk/jindun.apk";

        try{
            i.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }catch (Exception e){
            APPLog.zxhLog(TAG + Log.getStackTraceString(e));
        }

    }
}



